import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math.vector";
import { DefaultStage } from "../default-stage";
import { Landscape } from "./landscape";
import { Soldier } from "./soldier";
import { Random } from "babylon-lib/tool/random";
import { AnimationFrame, Utils } from "babylon-lib/index";
import * as Data from '../../data/data';


class SoldierManager {

    private static _count = 8;
    private static _overReq = {};

    public static soldiers: Array<Soldier> = [];

    public static alivedSoldiers: Array<Soldier> = [];

    public static initialize(stage: DefaultStage): void {
        this.initializeSoldiers(stage);
    }

    public static bindData(stage: DefaultStage): void {
        const _this = SoldierManager;
    }

    public static updateAlivedSoldiers(): void {
        this.alivedSoldiers.length = 0;
        for (const sd of this.soldiers) {
            if (sd.alive) this.alivedSoldiers.push(sd);
        }
        if (this.alivedSoldiers.length === 0) {
            Data.taskDone.value = true;
            AnimationFrame.throttleByTime(this._overReq, 2000, () => {
                Data.gameOn.value = false;
            }, false);
        }
    }

    private static initializeSoldiers(stage: DefaultStage): void {
        const center = Landscape.coreCenter;
        const range = Landscape.coreExtend;
        const march = new Vector3().copyFrom(Landscape.zoneCenter).subtractInPlace(Landscape.coreCenter).normalize();
        march.y = 0;
        march.x += 0.01;
        march.normalize();
        for (let i = 0; i < this._count; i++) {
            const position = new Vector3(Random.float(-1, 1), 0, Random.float(-1, 1)).normalize().scaleInPlace(Random.float(0, range));
            position.addInPlace(center);
            const soldier = new Soldier('soldier+' + Utils.id, stage.mainScene, {});
            soldier.entity.position.copyFrom(position);
            soldier.turn(march);
            this.soldiers.push(soldier);
        }
        this.alivedSoldiers = [...this.soldiers];
    }

}


export { SoldierManager };